package net.cohoivang.web;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.LinkedList;
import com.mysql.jdbc.CommunicationsException;

public class OurStatement extends OurStatementBase{

	OurConnection conn;
	Statement stmt;
	OurStatement(OurConnection conn) {
		this.conn = conn;
	}
	
	private final LinkedList<String> laterSqls = new LinkedList<String>();
	@Override
	public void executeUpdateBatch(OurConnection oc, int batchSize)
			throws SQLException {
		Statement stmt = null;
		while (batchSize > 0) {
			String sql;
			synchronized (laterSqls) {
				if (laterSqls.isEmpty()) {
					break;
				}
				sql = laterSqls.removeFirst();
				batchSize--;				
			}
			try {
				if (stmt == null) {
					stmt = oc.createRealStatement();
					System.out.println("SQLUpdateLater :" + sql);				
				}
				stmt.executeUpdate(sql);
			} catch (CommunicationsException ex) {
				System.out.println("SQLUpdateLaterRetry :" + sql);
				oc.reopenConnection();
				stmt = oc.createRealStatement();
				stmt.executeUpdate(sql);
			}
		}
		if (stmt != null) {
			stmt.close();
		}
	}
	
	public void executeUpdateLater(String sql) {
		synchronized (laterSqls) {
			laterSqls.add(sql);
		}
		TradingDbThread.instance.add(this);
	}

	@Override
	public void close() throws SQLException {
		if (stmt != null) {
			stmt.close();
		}
	}
	
	public ResultSet executeQuery(String sql) throws SQLException {
		try {
			if (stmt == null) {
				stmt = conn.createRealStatement();
			}
			System.out.println("SQLQuery: " + OurPrepareStatement.head(sql));
			return stmt.executeQuery(sql);
		} catch (CommunicationsException ex) {
			System.out.println("SQLQueryRetry: " + sql);
			conn.reopenConnection();
			stmt = conn.createRealStatement();
			return stmt.executeQuery(sql);
		} catch (Exception ex) {
			System.out.println("excute Query AAAAAAAAAAAAAAAAA");
			conn.reopenConnection();
			stmt = conn.createRealStatement();
			return stmt.executeQuery(sql);
		}			
	}
	
	public int executeUpdate(String sql) throws SQLException {
		try {
			if (stmt == null) {
				stmt = conn.createRealStatement();
			}
			System.out.println("SQLUpdate :" + OurPrepareStatement.head(sql));
			return stmt.executeUpdate(sql);
		} catch (CommunicationsException ex) {
			System.out.println("SQLUpdateRetry: " + sql);
			conn.reopenConnection();
			stmt = conn.createRealStatement();
			return stmt.executeUpdate(sql);
		}
	}
}
